package cn.nawang.ebeim.uc;

import java.awt.MouseInfo;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.embedded.browser.ChromeSettings;
import org.embedded.browser.ChromeWindow;
import org.embedded.browser.Chromium;
import org.embedded.browser.TitleChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esotericsoftware.minlog.Log;

import cn.nawang.ebeim.client.DownloadProcessBarThread;
import cn.nawang.ebeim.client.util.PathUtil;
import cn.nawang.ebeim.uc.util.ConfigUtil;
import cn.nawang.ebeim.uc.util.SystemUtil;
import javafx.application.Application;

public class LoginUI extends Thread{
  private Display display;
  private Shell shell;
  private Rectangle displayRect;
  private int x = 0;
  private int y = 0;
  private int width = 412;
  private int height = 592;
  private Composite titleComposite;
  private Composite mainComposite;
  private Tray tray;
  private TrayItem trayItem;
  private Label minLl;
  private Label closeLl;
  private Label helpLl;
  private Label lockLl;
  private Label titleLl;
  private Label ybaLl;
  private Chromium chromium;
  private String beforeTitle="";//记录发生页面跳转前的标题
  private String beforeUrl="";//记录发生页面跳转前的URL，目前没有直接获取页面URL的接口
  private String lockUrl = "";//锁屏前的url
  public static String isOpenDialog = "";
  private CustomDialog customDialog;
  private int currentX = -1 ;//记录当前窗体位置x坐标
  private int currentY = -1;//记录当前窗体y坐标
  private double mouseX ;
  private double mouseY ;
  private static Date lastActiveTime = new Date();//最近活跃的时间
  private static long lockTime =Long.parseLong(SystemUtil.read("lock_time"));//锁屏周期  -1表示不开启
  private boolean isNotLock = true;//锁屏状态，默认没锁
  private String userid="";

  private static final Logger LOG = LoggerFactory.getLogger(LoginUI.class);
  
  private String path(){
    File rootDir = new File(PathUtil.getClassPath());
    String imgPath = rootDir + "/others/";
    return imgPath;
  }

  public LoginUI() {
    display = new Display();
    displayRect = display.getBounds();
    shell = new Shell(display, SWT.NO_TRIM | SWT.NONE|SWT.PUSH|SWT.COLOR_WIDGET_DARK_SHADOW);
    shell.setBackgroundMode(SWT.INHERIT_DEFAULT);
    RGB shellRgb = new RGB(20, 51, 83);
    Color shellbkColor = new Color(Display.getDefault(), shellRgb);
    shell.setBackground(shellbkColor);
    titleComposite = new Composite(shell, SWT.INHERIT_DEFAULT);// 设置用于添加关闭、最小化用的画板
    titleComposite.setBounds(1, 1, width-1, 29);
    customDialog = new CustomDialog(shell,"");
    RGB rgb = new RGB(17, 110, 185);
    Color bkColor = new Color(Display.getDefault(), rgb);
    titleComposite.setBackground(bkColor);// 设置标题背景色
    mainComposite = new Composite(shell, SWT.NONE);// 设置主画板
    mainComposite.setBounds(1, 29, width-2, height - 30);
    chromium = new Chromium(mainComposite, SWT.NONE,"about:blank",new ChromeSettings().right_button(false, true));
//    chromium = ChromiumSingleton.getInstance(mainComposite, SWT.NONE);
    final Image minImg = new Image(display, path() + "image/min.png");
    final Image closeImg = new Image(display, path() + "image/close.png");
    final Image helpImg = new Image(display, path() + "image/help.png");
    final Image lockImg = new Image(display, path() + "image/lock.png");
    final Image close_hoverImg = new Image(display, path() +"image/close_hover.png");
    final Image min_hoverImg = new Image(display, path() +"image/min_hover.png");
    final Image min_clickImg = new Image(display, path() +"image/min_click.png");
    final Image close_clickImg = new Image(display, path() +"image/close_click.png");
    final Image lockingImg = new Image(display, path() + "image/locking.png");
    final Image titleLogo = new Image(display, path()+"image/titleLogo.png");
    titleLl = new Label(titleComposite, SWT.PUSH);
    titleLl.setImage(titleLogo);
    titleLl.setBounds(6, 6, 15, 15);
    ybaLl = new Label(titleComposite, SWT.PUSH);
    ybaLl.setText("易备安");
    ybaLl.setFont(new Font(display,"微软雅黑",10,SWT.NORMAL));//设置文字的字体字号
    ybaLl.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
    ybaLl.setBounds(27, 4, 100, 29);
    minLl = new Label(titleComposite, SWT.PUSH);
    minLl.setImage(minImg);
    minLl.setBounds(width-50, 3, 23, 23);
    minLl.setToolTipText("最小化");
    closeLl = new Label(titleComposite, SWT.PUSH);
    closeLl.setImage(closeImg);
    closeLl.setBounds(width-27, 3, 23, 23);
    closeLl.setToolTipText("关闭");
    helpLl = new Label(titleComposite, SWT.PUSH);
    helpLl.setImage(helpImg);
    helpLl.setBounds(width-97, 3, 23, 23);
    helpLl.setToolTipText("帮助");
    lockLl = new Label(titleComposite, SWT.PUSH);
    lockLl.setImage(lockImg);
    lockLl.setBounds(width-70,3,23,23);
    lockLl.setToolTipText("锁屏");
//    if(lockTime!=-1){
      getMouseXY();//监听鼠标移动
//    }
    final MouseListener lockLlMou = new MouseListener(){//锁屏跳转监听
      @Override
      public void mouseUp(MouseEvent arg0) {
        chromium.setUrl("http://127.0.0.1:" + ConfigUtil.getRestServerPort() + "/web/html/login.html");
        lockUrl = beforeUrl;//锁屏记录当前正在使用的界面（url）
        isNotLock = false;
        lockLl.setImage(lockingImg);
        if(isOpenDialog!=""){
          customDialog.CloseDialog();
        }
      }
      
      @Override
      public void mouseDown(MouseEvent arg0) {
        
      }
      
      @Override
      public void mouseDoubleClick(MouseEvent arg0) {
        
      }
    };
    
    minLl.addMouseTrackListener(new MouseTrackListener() {
      
      @Override
      public void mouseHover(MouseEvent arg0) {
        // TODO Auto-generated method stub
        minLl.setImage(min_hoverImg);
      }
      
      @Override
      public void mouseExit(MouseEvent arg0) {
        // TODO Auto-generated method stub
        minLl.setImage(minImg);
      }
      
      @Override
      public void mouseEnter(MouseEvent arg0) {
      }
    });

    closeLl.addMouseTrackListener(new MouseTrackListener() {
      
      @Override
      public void mouseHover(MouseEvent arg0) {
        // TODO Auto-generated method stub
        closeLl.setImage(close_hoverImg);
      }
      
      @Override
      public void mouseExit(MouseEvent arg0) {
        // TODO Auto-generated method stub
        closeLl.setImage(closeImg);
      }
      
      @Override
      public void mouseEnter(MouseEvent arg0) {
      }
    });
    
    shell.addListener(SWT.Close, new Listener() {
      
      @Override
      public void handleEvent(Event e) {
        e.doit = false; 
        shell.setVisible(false); 
      }
  });
    setUIcenter();// 设置窗体居中
    move();// 窗体拖动
    trayShow();//显示系统栏图标

    helpLl.addMouseListener(new MouseAdapter(){
      public void mouseUp(MouseEvent e){
        try {
          Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://new.ebeim.com/?c=menus&a=service");
         } catch (IOException e1) {
          e1.printStackTrace();
         }
      }
    });
    
    minLl.addMouseListener(new MouseAdapter() {// 最小化按钮鼠标点击事件监听
      public void mouseUp(MouseEvent e) {
        minLl.setImage(minImg);
        shell.setMinimized(true);// 最小化窗口
      }
      
      public void mouseDown(MouseEvent e){
        minLl.setImage(min_clickImg);
      }
    });

    closeLl.addMouseListener(new MouseAdapter() {// 关闭按钮鼠标点击事件监听
      public void mouseUp(MouseEvent e) {
        shell.setVisible(false);
      }
      public void mouseDown(MouseEvent e){
        closeLl.setImage(close_clickImg);
      }
    });
    
    chromium.addTitleChangeListener(new TitleChangeListener() {//监听标题是否发生改变,title是发生跳转后的标题
      
      public void TitleChanged(String titleUrl, Chromium c)
      { 
//        userid = SystemUtil.read("user.id");
        lastActiveTime = new Date();//修改活跃时间                                                
        String[] arr= titleUrl.split("\\|");//字符"|","*","+"都得加上转义字符，前面加上"\\"
        String title = arr[0];
        String url =arr[1];//记录跳转前的URL
//        if(userid!=null&&!userid.contains("")){//
//          
//        }
        if(url.contains("login.html")
            ||url.contains("forgetUser.html")
            ||url.contains("forgetPwd.html")
            ||url.contains("binding.html")
            ||url.contains("noRelation.html")
            ||url.contains("reset.html")
            ||url.contains("unBinding.html")){//如果是这几个界面，去除手动锁屏
          lockLl.removeMouseListener(lockLlMou);
        }else{
          if(lockLl.getListeners(SWT.MouseUp).length==0){//避免多次界面跳转重复添加监听
            lockLl.addMouseListener(lockLlMou);
          }
        }
        
        if(isNotLock == false){//如果是锁屏状态，则将锁图标变成黄色
          lockLl.setImage(lockingImg);
          if(isOpenDialog!=""){        //正常登陆isOpenDialog是为空的，isNotLock为false表示锁定
            customDialog.CloseDialog();//两者合起来判断表示锁屏状态下是否有弹窗打开，有则隐藏
          }
        }
        if(isNotLock == false&&
            (!url.contains("login.html")
                &&!url.contains("forgetUser.html")
                &&!url.contains("forgetPwd.html")
                &&!url.contains("binding.html")
                &&!url.contains("noRelation.html")
                &&!url.contains("reset.html")
                &&!url.contains("unBinding.html"))
                &&!lockUrl.equals("")){//如果是锁屏状态，则解锁，以上几个界面因为没有锁屏功能，因此也无解锁功能
          chromium.setUrl("http://127.0.0.1:" + ConfigUtil.getRestServerPort()+ lockUrl );//跳转到锁屏前的页面
          if(isOpenDialog!=""){
            customDialog.ShowDialog();
          }
          lockUrl = "";//解锁后清空之前保留的锁定url
          if(lockTime!=-1){
            startThread();//解锁，启动检测活跃线程
          }
          isNotLock = true;
          lockLl.setImage(lockImg);
        }else if(beforeUrl.contains("login.html")&&(
            !url.contains("forgetUser.html")
            &&!url.contains("forgetPwd.html")
            &&!url.contains("binding.html")
            &&!url.contains("noRelation.html")
            &&!url.contains("reset.html")
            &&!url.contains("unBinding.html"))){//正常登陆的时候开启检测是否有操作的线程
          if(lockTime!=-1){
            startThread();
          }
        }
        
        if(title!=null&&title.contains("弹窗")){
          if(title.equals("文件夹弹窗")||title.equals("保险箱弹窗")||title.equals("文件弹窗")){
            isOpenDialog = "文件夹弹窗";
          }
          customDialog.setTitle(title);
          customDialog.setUrl(url);
          customDialog.open();
        }else{
          
        }
        if(beforeTitle==null){//打开程序访问登录页的时候
          shell.setVisible(true);
        }else if(beforeTitle.equals("小窗口")){//如果跳转前标题与跳转后的标题不等，则判定未发生跳转，所以要确保前端页面标题不重复
//          shell.setVisible(false);
          shell.setBounds(0, 0, 0, 0);
        }else{
          shell.setVisible(true);
        }
        if(title.equals("大窗口")){
          setSize(920,680);
          _setSize();
          titleComposite.setBounds(1, 1, width-2, 29);
          mainComposite.setBounds(1, 29, width-2, height - 30);
          minLl.setBounds(width-50, 3, 23, 23);
          closeLl.setBounds(width-27, 3, 23, 23);
          helpLl.setBounds(width-97, 3, 23, 23);
          lockLl.setBounds(width-70,3,23,23);
          titleLl.setBounds(6,6,15,15);
          beforeUrl = url;
          beforeTitle = title;
          shell.setVisible(true);
        }else if(title.equals("小窗口")){
          setSize(410,593);
          _setSize();
          titleComposite.setBounds(1, 1, width-2, 29);
          mainComposite.setBounds(1, 29, width-2, height - 30);
          minLl.setBounds(width-50, 3, 23, 23);
          closeLl.setBounds(width-27, 3, 23, 23);
          helpLl.setBounds(width-97, 3, 23, 23);
          lockLl.setBounds(width-70,3,23,23);
          titleLl.setBounds(6,6,15,15);
          shell.setActive();
          shell.setVisible(true);
        }
        shell.open();
        beforeUrl = url;
        beforeTitle = title;
      }
      int i ;
  });
}



  /**
   * 显示系统栏图标
   */
  private void trayShow() {

    Image iIcon = new Image(display, path() + "image/logo.png");
    // 取系统中预置的图标，省得测试运行时还得加个图标文件
    shell.setImage(iIcon);
    shell.setText("易备安");
    // 构造系统栏控件
    tray = display.getSystemTray();
    trayItem = new TrayItem(tray, SWT.NONE);
    trayItem.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        toggleDisplay(shell, tray);
      }
    });

    final Menu trayMenu = new Menu(shell, SWT.POP_UP);
    MenuItem showMenuItem = new MenuItem(trayMenu, SWT.PUSH);
    String showTable = "显示窗口(&s)";
    try {
      showTable = java.net.URLDecoder.decode(showTable,"utf-8");
    } catch (UnsupportedEncodingException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    showMenuItem.setText(showTable);

    // 显示窗口，并隐藏系统栏中的图标
    showMenuItem.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        toggleDisplay(shell, tray);
      }
    });

    trayMenu.setDefaultItem(showMenuItem);

    new MenuItem(trayMenu, SWT.SEPARATOR);

    // 系统栏中的退出菜单，程序只能通过这个菜单退出
    MenuItem exitMenuItem = new MenuItem(trayMenu, SWT.PUSH);
    String exitStr = "退出程序(&x)";
    try {
      exitStr = java.net.URLDecoder.decode(exitStr,"utf-8");
    } catch (UnsupportedEncodingException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    exitMenuItem.setText(exitStr);
    
    exitMenuItem.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        MessageBox mb = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
        mb.setText("提示");
        mb.setMessage("确定要退出易备安吗?");
        int rc = mb.open();
        if (e.doit == (rc == SWT.OK)) {//确认退出
          //// 做窗口关闭事件
          cn.nawang.ebeim.client.AppMain.exitClient();
          RestServer.destory();
          ChromeWindow.Close(false);
          ChromeWindow.Shutdown();
          Log.info("不删除userid了");
          tray.dispose();// 退出系统隐藏图标
          chromium.dispose();
          shell.dispose();
          System.exit(0);
          try {
            SystemUtil.delete("user.id");//退出删除user.id和customer.id
            SystemUtil.delete("customer.id");
          } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
          }
        } else if (e.doit == (rc == SWT.CANCEL)) {//选择取消

        }

      }
    });

    // 在系统栏图标点击鼠标右键时的事件，弹出系统栏菜单
    trayItem.addMenuDetectListener(new MenuDetectListener() {
      public void menuDetected(MenuDetectEvent e) {
        trayMenu.setVisible(true);
      }
    });

    trayItem.setImage(shell.getImage());

  }


  /**
   * 窗口是可见状态时，则隐藏窗口，同时把系统栏中图标删除 窗口是隐藏状态时，则显示窗口，并且在系统栏中显示图标
   * 
   * @param shell 窗口
   * @param tray 系统栏图标控件
   */
  private static void toggleDisplay(Shell shell, Tray tray) {
    try {
      shell.setVisible(!shell.isVisible());
      tray.getItem(0).setVisible(true);
      if (shell.getVisible()) {
        shell.setMinimized(false);
        shell.setActive();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // 设置窗体居中
  private void setUIcenter() {
    x = Display.getCurrent().getClientArea().width / 2 - shell.getShell().getSize().x / 2;
    y = Display.getCurrent().getClientArea().height / 2 - shell.getSize().y / 2;
    shell.setLocation(x,y);
  }


  private void _setBounds(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

  }
  
  public void _setSize(){
    shell.setActive();
    if(currentX!=-1||currentY!=-1){
      shell.setBounds(currentX, currentY, width, height);//可设置窗体自动居中
//      OS.SetWindowPos(shell.handle,OS.HWND_TOP,currentX,currentY,width,height, SWT.NULL);//设置窗口显示最前
    }else{
      shell.setBounds((displayRect.width - width) >> 1,(displayRect.height - height) >> 1, width, height);//可设置窗体自动居中  
//      OS.SetWindowPos(shell.handle,OS.HWND_TOP,(displayRect.width - width) >> 1,(displayRect.height - height) >> 1,width,height, SWT.NULL);//设置窗口显示最前
    }
    chromium.setBounds(0, 0, width, height);
  }

  
  
  /**
   * 正常大小(一般与fullScreen配合使用)
   */
  public void normalScreen() {
    _setBounds(x, y, width, height);
  }

  /**
   * 最小化窗体
   */
  public void minScreen() {
    shell.setMinimized(true);
  }

  /**
   * 设置窗体宽高,自动居中
   * 
   * @param width
   * @param height
   */
  public void setSize(int width, int height) {
    _setBounds(x, y, width, height);
  }

  /**
   * 设置窗体坐标和宽高
   * 
   * @param x
   * @param y
   * @param width
   * @param height
   */
  public void setBounds(int x, int y, int width, int height) {
    _setBounds(x, y, width, height);
  }

  /**
   * 消息循环
   */
  public void msgLoop() {

    shell.open();
    shell.setActive();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    shell.dispose();
    display.dispose();
  }

  /**
   * 跳转页面
   * 
   * @param url
   */
  public void setUrl(String url) {
    chromium.setUrl(url);
  }

  /**
   * 窗体拖动
   */
  public void move() {
    Listener listener = new Listener() {
      int startX, startY;

      public void handleEvent(Event e) {
        if (e.type == SWT.MouseDown && e.button == 1) {
          startX = e.x;
          startY = e.y;
          currentX = e.x;
          currentY = e.y;
        }
        if (e.type == SWT.MouseMove && (e.stateMask & SWT.BUTTON1) != 0) {
          org.eclipse.swt.graphics.Point p = (org.eclipse.swt.graphics.Point) shell.toDisplay(e.x, e.y);
          p.x -= startX;
          p.y -= startY;
          currentX = p.x;
          currentY = p.y;
          shell.setLocation(p);
        }
      }
    };
    titleComposite.addListener(SWT.MouseDown, listener);
    titleComposite.addListener(SWT.MouseMove, listener);
    ybaLl.addListener(SWT.MouseDown, listener);
    ybaLl.addListener(SWT.MouseMove, listener);
  }
  
  /**
   * 鼠标移动监听
   * @author lizh
   * @Description: 获取当前鼠标的位置，用于判断鼠标是否发生过移动，周期是一秒获取一次鼠标坐标
   * @date 2015年11月17日上午10:55:27
   *
   * @修改人 
   * @修改日期
   */
  public void getMouseXY(){
    Timer timer = new Timer();
    timer.schedule(new TimerTask(){
      @Override
      public void run(){
        Point point = MouseInfo.getPointerInfo().getLocation();
        if(mouseX!=point.getX()&&mouseY!=point.getY()){
          lastActiveTime = new Date();
//          System.out.println("鼠标有移动");
        }else{
//          System.out.println("鼠标没有移动");
        }
        mouseX = point.getX();
        mouseY = point.getY();
//        System.out.println("Locotion:x="+point.getX()+" y="+point.getX());
      }
    },0,1000);
  }
  
  
  /**
   * 启动线程，锁屏处理
   */
  private void startThread() {
      new Thread() {
          public void run() {
              try {
                while(isNotLock){
                  Date now = new Date();
                  long nowTime = now.getTime();
//                  LOG.debug("锁屏线程有起");
                  lockTime = Long.parseLong(SystemUtil.read("lock_time"));//锁屏周期  -1表示不开启
                  if(lockTime==-1){
                    isNotLock = false;//退出线程
                  }else if(nowTime - lastActiveTime.getTime() > lockTime&&lockTime!=-1){//当前时间减去最近活跃时间，如果大于锁屏周期，则锁屏
                    chromium.setUrl("http://127.0.0.1:" + ConfigUtil.getRestServerPort() + "/web/html/login.html");
                    lockUrl = beforeUrl;//锁屏记录当前正在使用的界面（url）
                    isNotLock = false;//编辑为没有打开（锁屏）
                  }else{
                      try {
                        //设置定时时间为2000毫秒
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                  }
                }
              }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } finally {
                 
              }
          }
      }.start();
  }
}
